import json
import socket
import string
import sys
import time
from hashlib import md5
from random import randint, sample

import requests
import wmi

from util.utils import get_logger

c = wmi.WMI()


class APIWrapper(requests.Session):
    def __init__(self):
        super().__init__()

    def get_json(self, url=None, method="post", headers=None, params=None, json=None, data=None, **kwargs):
        """
        json接口通用请求方法
        :param method: 请求方法, 默认为post
        :param url:     请求URL
        :param params:  请求参数
        :param data:    请求数据
        :return: json转换出的字典
        """
        ip = kuai_api.get_dps("901715501690712", "17y42w7qtfc44ypijvr3165qn12iljff", 1)
        self.proxy_dict = {'http': 'http://' + ip, 'https': 'http://' + ip}
        try:
            if ip:
                proxies = self.proxy_dict
                timeout = self.timeout
            else:
                proxies = {}
                timeout = 2
        except:
            proxies = {}
            timeout = 2
        self.logger.info('执行ip:{}'.format(self.proxy_dict))
        r = getattr(self, method)(url, headers=headers, json=json, data=data, params=params, proxies=proxies,
                                  timeout=timeout, **kwargs)
        return r.json()
        # try:
        #     r = getattr(self, method)(url, headers=headers, json=json, data=data, params=params, proxies=proxies,timeout=timeout, **kwargs)
        #     return r.json()
        # except:
        #     return -1


class YuanAPI(APIWrapper):
    def __init__(self):
        super(YuanAPI, self).__init__()
        self.headers["Content-Type"] = "multipart/form-data"
        # self.add_dingshi_url = 'http://yesmywine.yxy5g.com/api/index/regularRushPurchase'
        # self.qj_success_url = 'http://yesmywine.yxy5g.com/api/index/orderCreate'
        # self.install_url = 'http://yesmywine.yxy5g.com/api/index/softwareinstall'
        # self.exe_check_url = 'http://yesmywine.yxy5g.com/api/index/checking'
        self.add_dingshi_url = ''
        self.qj_success_url = ''
        self.install_url = ''
        self.exe_check_url = ''

    def get_hostname(self):
        hostname = socket.gethostname()
        return hostname

    def yingpan(self):
        # # 硬盘序列号
        cc = ""
        for physical_disk in c.Win32_DiskDrive():
            cc += physical_disk.SerialNumber
        return cc

    def cpuid(self):
        # CPU序列号
        cc = ""
        for cpu in c.Win32_Processor():
            cc += cpu.ProcessorId.strip()

        return cc

    def device_str(self):
        cpuid = self.cpuid()
        yinpan = self.yingpan()
        return cpuid + '|' + yinpan

    def add_dingshi(self, goods_id, c_time, token, mobile):
        data = {
            'goods_id': goods_id,
            'c_time': c_time,
            'token': token,
            'mobile': mobile
        }
        code = 200
        try:
            res = requests.post(self.add_dingshi_url, data=data, timeout=1)
            code = res.json().get('code')
        except:
            pass
        return code

    def qj_success(self, mobilenumber, orderStr):
        data = {
            'mobilenumber': mobilenumber,
            'devicenumber': self.device_str(),
            'orderStr': orderStr
        }
        code = 200
        try:
            res = requests.post(self.qj_success_url, data=data, timeout=1)
            code = res.json().get('code')
        except:
            pass
        return code

    def install(self):
        data = {
            'installIp': self.get_hostname(),
            'deviceInfoStr': self.device_str(),
        }
        code = 200
        try:
            res = requests.post(self.install_url, data=data, timeout=1)
            code = res.json().get('code')
        except:
            pass
        return code

    def exe_check(self):
        data = {
            'ipStr': self.get_hostname(),
            'deviceInfoStr': self.device_str(),
        }
        code = 200
        try:
            res = requests.post(self.exe_check_url, data=data, timeout=1)
            code = res.json().get('code')
        except:
            pass

        return code


class KuaiAPI(APIWrapper):
    def __init__(self):
        super(KuaiAPI, self).__init__()
        self.headers["Content-Type"] = "multipart/form-data"
        self.balance_url = 'https://dev.kdlapi.com/api/getaccountbalance'
        self.orders_url = 'https://dev.kdlapi.com/api/getaccountorders'
        self.order_info_url = 'https://dev.kdlapi.com/api/getorderinfo'
        self.dps_url = 'http://dps.kdlapi.com/api/getdps'
        self.dps_balance_url = 'https://dps.kdlapi.com/api/getipbalance'
        self.kps_url = 'http://kps.kdlapi.com/api/getkps'

    def get_balance(self, order_id, api_key):
        balance_url = self.balance_url + '?orderid={}&signature={}'.format(order_id, api_key)
        r = requests.get(balance_url)

    def get_orders(self, order_id, api_key):
        order_url = self.orders_url + '?orderid={}&signature={}'.format(order_id, api_key)
        r = requests.get(order_url)

    def get_order_info(self, order_id, api_key):
        order_info_url = self.order_info_url + '?orderid={}&signature={}'.format(order_id, api_key)
        r = requests.get(order_info_url)

    def get_dps(self, order_id, api_key, num):
        order_id = "901715501690712"
        api_key = "17y42w7qtfc44ypijvr3165qn12iljff"
        dps_url = self.dps_url + '?orderid={}&signature={}&num={}'.format(order_id, api_key, num)
        r = requests.get(dps_url)
        return r.text

    def get_dps_balance(self, order_id, api_key):
        dps_balance_url = self.dps_balance_url + '?orderid={}&signature={}'.format(order_id, api_key)
        r = requests.get(dps_balance_url)
        data = r.json()
        if data.get('data', {}).get('balance'):
            return data.get('data', {}).get('balance')
        else:
            return 0

    def get_kps(self, order_id, api_key, num):
        kps_url = self.kps_url + '?orderid={}&signature={}&num={}'.format(order_id, api_key, num)
        r = requests.get(kps_url)


class YeMaiAPI(APIWrapper):
    def __init__(self, proxy_ip=None, timeout=1):
        super(YeMaiAPI, self).__init__()
        self.logger = get_logger('yemai_api')
        self.headers["Content-Type"] = "application/json"
        self.yemaijiu_url = "https://o2o.yesmywine.com/topapi/"
        self.yemaijiu_activity_goods_url = "https://mk-ys.yesmywine.com/promotion/getActivityGoods?activity_id={}"
        self.yemaijiu_activity_detail_url = "https://mk-ys.yesmywine.com/goods/activitydetails"
        self.yemaijiu_activity_yuyue_url = "https://mk-ys.yesmywine.com/promotion/subscribe/run"
        self.yemaijiu_order_create_url = "https://mk-ys.yesmywine.com/order/create"
        self.proxy_ip = proxy_ip or ''
        self.timeout = timeout or 1
        self.proxy_dict = {'http': 'http://' + self.proxy_ip, 'https': 'http://' + self.proxy_ip}

    def _get_timestamp(self):
        return str(int(time.time() * 1000))

    def _get_bbc_sec(self, timestamp):
        content = "gedeyingxiang-yesmywine-1499maotai" + timestamp
        m5 = md5()
        m5.update(content.encode("utf-8"))
        bbc_sec = m5.hexdigest().lower()
        return bbc_sec

    def _get_headers(self):
        ts = self._get_timestamp()
        bbc_sec = self._get_bbc_sec(ts)
        headers = {
            "bbc-sec": bbc_sec,
            "bbc-timestamp": ts,
            "User-Agent": 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1',
            "Host": 'o2o.yesmywine.com',
            "Accept": "*/*",
            "Content-Type": "application/json",
            "Accept-Encoding": "gzip,deflate",
            "Accept-Language": "zh-CN,en-US;q=0.9",
            "Origin": "https://o2o.yesmywine.com"
        }
        return headers

    def api_sms(self, mobile):
        # 发送验证码
        sec_header = self._get_headers()
        sec_header['Referer'] = "https://m.o2o.yesmywine.com/signin"
        data = {"mobile": mobile, "format": "json", "v": "v1", "method": "user.vue.sendSms"}

        res = self.get_json(self.yemaijiu_url, headers=sec_header, json=data)
        self.logger.info(
            '函数名:{},功能:{},结果:{},参数:{},请求头:{}'.format(sys._getframe().f_code.co_name, '发送验证码', res, data, sec_header))
        if res == -1:
            return 0, '网络错误'
        if res.get("data", {}).get("status") == "success":
            return 1, res.get("data", {})
        else:
            return 0, res['msg']

    def api_login(self, mobile, sms_letter):
        # 登录
        sec_header = self._get_headers()
        sec_header['Referer'] = "https://m.o2o.yesmywine.com/signin"
        device_number_1 = randint(867139041292069, 967139041292069)
        device_number_2 = randint(867139041292077, 967139041292077)
        data = {"account": mobile,
                "vcode": None,
                "sms_code": sms_letter,
                "type": "android",
                "clientid": ''.join(sample(string.ascii_letters + string.digits, 32)).lower(),
                "device_number": "{},{}".format(device_number_1, device_number_2),
                "origin": 1,
                "tag_type": None,
                "format": "json",
                "v": "v1",
                "method": "user.vue.login"}
        res = self.get_json(self.yemaijiu_url, headers=sec_header, json=data)
        self.logger.info(
            '函数名:{},功能:{},结果:{},参数:{},请求头:{}'.format(sys._getframe().f_code.co_name, '登录', res, data, sec_header))
        if res == -1:
            return 0, '网络错误'
        if res.get("errorcode") == 0:
            return 1, res.get("data", {})
        else:
            return 0, res['msg']

    def api_huiyuan_list(self, access_token):
        # 会员列表
        sec_header = self._get_headers()
        sec_header['Referer'] = "https://m.o2o.yesmywine.com/1member1bb"
        data = {"accessToken": access_token,
                "format": "json",
                "v": "v1",
                "method": "member.index"}

        # res = requests.post(self.yemaijiu_url, headers=sec_header, json=data)
        res = self.get_json(self.yemaijiu_url, headers=sec_header, json=data)
        self.logger.info(
            '函数名:{},功能:{},结果:{},参数:{},请求头:{}'.format(sys._getframe().f_code.co_name, '会员列表', res, data, sec_header))
        if res == -1:
            return 0, '网络错误'
        if res.get("errorcode") == 0:
            return 1, res.get("data", {})
        else:
            return 0, res['msg']

    def api_order_list(self, access_token, status, page_no):
        # 订单列表
        # status 1 全部  2代付款 3待配送
        sec_header = self._get_headers()
        sec_header['Referer'] = "https://m.o2o.yesmywine.com/order?type=ALL"
        data = {"accessToken": access_token,
                "page_no": page_no,
                "page_size": 20, "format": "json", "v": "v1", "method": "trade.list"}
        if status == 2:  # 待付款
            data["status"] = "WAIT_BUYER_PAY"
        elif status == 3:  # 待配送
            data["status"] = "WAIT_SELLER_SEND_GOODS"
        elif status == 4:  # 已完成
            data["status"] = "TRADE_FINISHED"
        elif status == 5:  # 已关闭
            data["status"] = "TRADE_CLOSED_BY_SYSTEM"

        # res = requests.post(self.yemaijiu_url, headers=sec_header, json=data)
        res = self.get_json(self.yemaijiu_url, headers=sec_header, json=data)
        self.logger.info(
            '函数名:{},功能:{},结果:{},参数:{},请求头:{}'.format(sys._getframe().f_code.co_name, '订单列表', res, data, sec_header))
        if res == -1:
            return 0, '网络错误 order_list'
        if res.get("errorcode") == 0:
            return 1, res.get("data", {})
        else:
            return 0, res['msg']

    def api_order_detail(self, access_token, tid):
        # 订单详情
        sec_header = self._get_headers()
        sec_header['Referer'] = "https://m.o2o.yesmywine.com/order?type=ALL"
        data = {"accessToken": access_token,
                "tid": tid, "format": "json", "v": "v1", "method": "trade.get"}

        res = self.get_json(self.yemaijiu_url, headers=sec_header, json=data)
        self.logger.info(
            '函数名:{},功能:{},结果:{},参数:{},请求头:{}'.format(sys._getframe().f_code.co_name, '订单详情', res, data, sec_header))
        if res == -1:
            return 0, '网络错误 order_detail'
        if res.get("errorcode") == 0:
            return 1, res.get("data", {})
        else:
            return 0, res['msg']

    def api_zhifu_detail(self, access_token, tid):
        # 支付链接
        sec_header = self._get_headers()
        sec_header['Referer'] = "https://m.o2o.yesmywine.com/order?type=ALL"
        data = {"accessToken": access_token,
                "tid": tid, "format": "json", "v": "v1", "method": "trade.get"}

        res = self.get_json(self.yemaijiu_url, headers=sec_header, json=data)
        self.logger.info(
            '函数名:{},功能:{},结果:{},参数:{},请求头:{}'.format(sys._getframe().f_code.co_name, '订单详情', res, data, sec_header))
        if res == -1:
            return 0, '网络错误'
        if res.get("errorcode") == 0:
            return 1, res.get("data", {})
        else:
            return 0, res['msg']

    def api_address_list(self, access_token):
        # 地址列表
        sec_header = self._get_headers()
        sec_header['Referer'] = "https://m.o2o.yesmywine.com/address_list/false"
        data = {"accessToken": access_token, "format": "json", "v": "v1", "method": "member.address.list"}
        res = self.get_json(self.yemaijiu_url, headers=sec_header, json=data)
        self.logger.info(
            '函数名:{},功能:{},结果:{},参数:{},请求头:{}'.format(sys._getframe().f_code.co_name, '地址列表', res, data, sec_header))
        if res == -1:
            return 0, '网络错误'
        if res.get("errorcode") == 0:
            return 1, res.get("data", {})
        else:
            return 0, res['msg']

    def get_add_data(self, ssq, xq):
        r = requests.get('https://apis.map.qq.com/jsapi?qt=geoc&addr={}&key=UGMBZ-CINWR-DDRW5-W52AK-D3ENK-ZEBRC'
                         '&output=jsonp&pf=jsapi&ref=jsapi&cb=c'.format(ssq + xq))
        x = json.loads(r.text[2:-1])
        res = {
            'province': x['detail']['province'],
            'city': x['detail']['city'],
            'district': x['detail']['district'],
            'adcode': x['detail']['adcode'],
            'x': x['detail']['pointx'],
            'y': x['detail']['pointy'],
            'ssq': ssq,
            'xq': xq
        }
        return res

    # get_add_data('广东省深圳市南山区', '新屋村东区青年宿舍113室')

    def api_address_add(self, access_token, ssq, xq, mobile, name):
        # 添加地址
        sec_header = self._get_headers()
        sec_header['Referer'] = "https://m.o2o.yesmywine.com/address_list/false"
        address_data = self.get_add_data(ssq, xq)
        data = {"accessToken": access_token,
                "area": "{},{},{},{},{}".format(
                    address_data['ssq'] + address_data['xq'], address_data['city'], address_data['xq'],
                    address_data['y'], address_data['x']
                ),
                "addr": address_data['xq'], "mobile": mobile, "name": name, "def_addr": 1,
                "province": address_data['province'],
                "city": address_data['city'],
                "district": address_data['district'], "adcode": address_data['adcode'], "fromWap": 1,
                "tag": "no", "format": "json", "v": "v1", "method": "member.address.create"}
        res = self.get_json(self.yemaijiu_url, headers=sec_header, json=data)
        self.logger.info(
            '函数名:{},功能:{},结果:{},参数:{},请求头:{}'.format(sys._getframe().f_code.co_name, '添加地址', res, data, sec_header))
        if res == -1:
            return 0, '网络错误'
        if res.get("errorcode") == 0:
            return 1, res.get("data", {})
        else:
            return 0, res['msg']

    def api_address_delete(self, access_token, addr_id):
        # 删除地址
        sec_header = self._get_headers()
        sec_header['Referer'] = "https://m.o2o.yesmywine.com/address_list/false"
        data = {"accessToken": access_token, "addr_id": addr_id, "format": "json", "v": "v1",
                "method": "member.address.delete"}
        res = self.get_json(self.yemaijiu_url, headers=sec_header, json=data)
        self.logger.info(
            '函数名:{},功能:{},结果:{},参数:{},请求头:{}'.format(sys._getframe().f_code.co_name, '删除地址', res, data, sec_header))
        if res == -1:
            return 0, '网络错误'
        if res.get("errorcode") == 0:
            return 1, res.get("data", {})
        else:
            return 0, res['msg']

    def api_point_detail(self, access_token):
        # 签到列表查询
        sec_header = self._get_headers()
        sec_header['Referer'] = "https://m.o2o.yesmywine.com/mypointlist"
        data = {"accessToken": access_token, "format": "json", "page_no": 1,
                "page_size": 20, "v": "v1", "method": "member.point.detail"}
        res = self.get_json(self.yemaijiu_url, headers=sec_header, json=data)
        self.logger.info(
            '函数名:{},功能:{},结果:{},参数:{},请求头:{}'.format(sys._getframe().f_code.co_name, '签到列表查询', res, data, sec_header))
        if res == -1:
            return 0, '网络错误'
        if res.get("errorcode") == 0:
            return 1, res.get("data", {})
        else:
            return 0, res['msg']

    def api_point_checkinadd(self, access_token):
        # 每日签到
        sec_header = self._get_headers()
        sec_header['Referer'] = "https://m.o2o.yesmywine.com/checkin"
        data = {"accessToken": access_token, "format": "json", "v": "v1", "method": "user.vue.checkinAdd"}
        res = self.get_json(self.yemaijiu_url, headers=sec_header, json=data)
        self.logger.info(
            '函数名:{},功能:{},结果:{},参数:{},请求头:{}'.format(sys._getframe().f_code.co_name, '每日签到', res, data, sec_header))
        if res == -1:
            return 0, '网络错误'
        if res.get("errorcode") == 0:
            return 1, res.get("data", {})
        else:
            return 0, res['msg']

    def api_coupon_list(self, access_token, page_no, is_valid):
        # 我的优惠券列表
        # is_valid 1未使用 0已使用 2已过期
        sec_header = self._get_headers()
        sec_header['Referer'] = "https://m.o2o.yesmywine.com/coupon"
        data = {"accessToken": access_token, "format": "json", "page_no": page_no, "is_valid": is_valid,
                "page_size": 10, "v": "v1", "method": "member.coupon.all"}
        res = self.get_json(self.yemaijiu_url, headers=sec_header, json=data)
        self.logger.info(
            '函数名:{},功能:{},结果:{},参数:{},请求头:{}'.format(sys._getframe().f_code.co_name, '我的优惠券列表', res, data, sec_header))
        if res == -1:
            return 0, '网络错误'
        if res.get("errorcode") == 0:
            return 1, res.get("data", {})
        else:
            return 0, res['msg']

    def api_coupon_center(self, access_token, page_no, counpon_type):
        # 领劵中心优惠券列表
        # counpon_type all全部 platform平台券 selfshop自营券
        sec_header = self._get_headers()
        sec_header['Referer'] = "https://m.o2o.yesmywine.com/coupon_center"
        data = {"accessToken": access_token, "format": "json", "page_no": page_no, "type": counpon_type,
                "page_size": 10, "v": "v1", "method": "member.coupon.center"}
        res = self.get_json(self.yemaijiu_url, headers=sec_header, json=data)
        self.logger.info(
            '函数名:{},功能:{},结果:{},参数:{},请求头:{}'.format(sys._getframe().f_code.co_name, '领劵中心优惠券列表', res, data,
                                                     sec_header))
        if res == -1:
            return 0, '网络错误'
        if res.get("errorcode") == 0:
            return 1, res.get("data", {})
        else:
            return 0, res['msg']

    def api_coupon_get(self, access_token, coupon_id, counpon_type):
        # 领券 counpon_type: platform, selfshop
        sec_header = self._get_headers()
        sec_header['Referer'] = "https://m.o2o.yesmywine.com/coupon_center"
        data = {"accessToken": access_token, "coupon_id": coupon_id, "type": counpon_type, "format": "json", "v": "v1",
                "method": "member.coupon.get"}
        res = self.get_json(self.yemaijiu_url, headers=sec_header, json=data)
        self.logger.info(
            '函数名:{},功能:{},结果:{},参数:{},请求头:{}'.format(sys._getframe().f_code.co_name, '领券', res, data, sec_header))
        if res == -1:
            return 0, '网络错误'
        if res.get("errorcode") == 0:
            return 1, res.get("data", {})
        else:
            return 0, res['msg']

    def api_point_duihuan_list(self, access_token, page_no):
        # 积分可兑换列表
        sec_header = self._get_headers()
        sec_header['Referer'] = "https://m.o2o.yesmywine.com/point"
        data = {"accessToken": access_token, "format": "json", "page_no": page_no,
                "page_size": 10, "v": "v1", "method": "index.vue.pointList"}
        res = self.get_json(self.yemaijiu_url, headers=sec_header, json=data)
        self.logger.info(
            '函数名:{},功能:{},结果:{},参数:{},请求头:{}'.format(sys._getframe().f_code.co_name, '积分可兑换列表', res, data, sec_header))
        if res == -1:
            return 0, '网络错误'
        if res.get("errorcode") == 0:
            return 1, res.get("data", {})
        else:
            return 0, res['msg']

    def api_cart_list(self, access_token):
        # 购物车
        sec_header = self._get_headers()
        sec_header['Referer'] = "https://m.o2o.yesmywine.com/point"
        data = {"accessToken": access_token, "format": "json", "v": "v1", "method": "cart.count"}
        res = self.get_json(self.yemaijiu_url, headers=sec_header, json=data)
        self.logger.info(
            '函数名:{},功能:{},结果:{},参数:{},请求头:{}'.format(sys._getframe().f_code.co_name, '购物车', res, data, sec_header))
        if res == -1:
            return 0, '网络错误'
        if res.get("errorcode") == 0:
            return 1, res.get("data", {})
        else:
            return 0, res['msg']

    def api_cart_add(self, access_token, goods_id, sku_id):
        # 购物车
        sec_header = self._get_headers()
        sec_header['Referer'] = "https://m.o2o.yesmywine.com/goods/{}".format(goods_id)
        data = {"accessToken": access_token, "sku_id": sku_id, "quantity": 1, "new_self_sku_id": "", "mode": "fastbuy",
                "obj_type": "item", "tag_type": "null", "format": "json", "v": "v1", "method": "cart.add"}
        res = self.get_json(self.yemaijiu_url, headers=sec_header, json=data)
        self.logger.info(
            '函数名:{},功能:{},结果:{},参数:{},请求头:{}'.format(sys._getframe().f_code.co_name, '添加购物车', res, data, sec_header))
        if res == -1:
            return 0, '网络错误'
        if res.get("errorcode") == 0:
            return 1, res.get("data", {})
        else:
            return 0, res['msg']

    def api_real_auth(self, access_token, real_name, id_num):
        # 用户实名
        sec_header = self._get_headers()
        sec_header['Referer'] = "https://m.o2o.yesmywine.com/member/setting/real_auth"
        data = {"accessToken": access_token, "real_name": real_name, "id_number": id_num, "format": "json", "v": "v1",
                "method": "member.realName"}
        res = self.get_json(self.yemaijiu_url, headers=sec_header, json=data)
        self.logger.info(
            '函数名:{},功能:{},结果:{},参数:{},请求头:{}'.format(sys._getframe().f_code.co_name, '用户实名', res, data, sec_header))
        if res == -1:
            return 0, '网络错误'
        if res.get("errorcode") == 0:
            if res.get("data", {}).get('status') == 'success':
                return 1, res.get("data", {})
            else:
                return 0, res['msg']
        else:
            return 0, res['msg']

    def api_activity_goods(self, access_token, activity_id):
        # 活动id下的商品列表
        sec_header = self._get_headers()
        sec_header['Host'] = "mk-ys.yesmywine.com"
        sec_header['Referer'] = "https://m.o2o.yesmywine.com/maotai-active/index/{}".format(activity_id)
        sec_header['Token'] = access_token
        res = self.get_json(self.yemaijiu_activity_goods_url.format(activity_id), headers=sec_header, method='get')
        self.logger.info(
            '函数名:{},功能:{},结果:{},参数:{},请求头:{}'.format(sys._getframe().f_code.co_name, '活动id下的商品列表', res, '', sec_header))
        if res == -1:
            return 0, '网络错误'
        if res.get("msg") == 'success':
            return 1, res.get("data", {})
        else:
            return 0, res['msg']

    def api_good_detail(self, access_token, goods_id):
        # 商品详情
        sec_header = self._get_headers()
        sec_header['Host'] = "o2o.yesmywine.com"
        sec_header['Referer'] = "https://m.o2o.yesmywine.com/goods/{}".format(goods_id)
        sec_header['Origin'] = 'https://m.o2o.yesmywine.com'
        data = {"accessToken": access_token,
                "format": "json",
                "item_id": goods_id,
                "v": "v2",
                "method": "item.detail"}
        res = self.get_json(self.yemaijiu_url, headers=sec_header, json=data)
        self.logger.info(
            '函数名:{},功能:{},结果:{},参数:{},请求头:{}'.format(sys._getframe().f_code.co_name, '商品详情', res, data,
                                                     sec_header))
        if res == -1:
            return 0, '网络错误 good_detail'
        if res.get("errorcode") == 0:
            return 1, res.get("data", {})
        else:
            return 0, res['msg']

    def api_activity_good_detail(self, access_token, activity_id, goods_id, user_id):
        # 活动id下的商品详情
        sec_header = self._get_headers()
        sec_header['Host'] = "mk-ys.yesmywine.com"
        sec_header['Referer'] = "https://m.o2o.yesmywine.com/maotai-active/goodsInfo/{}/{}".format(goods_id,
                                                                                                   activity_id)
        sec_header['Token'] = access_token
        sec_header['Origin'] = 'https://m.o2o.yesmywine.com'
        data = {"accessToken": access_token, "activity_id": activity_id, "goods_id": goods_id, "user_id": user_id}
        res = self.get_json(self.yemaijiu_activity_detail_url, headers=sec_header, json=data)
        self.logger.info(
            '函数名:{},功能:{},结果:{},参数:{},请求头:{}'.format(sys._getframe().f_code.co_name, '活动id下的商品详情', res, data,
                                                     sec_header))
        if res == -1:
            return 0, '网络错误'
        if res.get("msg") == 'success':
            return 1, res.get("data", {})
        else:
            return 0, res['msg']

    def api_activity_good_yuyue(self, access_token, activity_id, addr_id, goods_id):
        # 活动id下的商品预约
        sec_header = self._get_headers()
        sec_header['Host'] = "mk-ys.yesmywine.com"
        sec_header['Referer'] = "https://m.o2o.yesmywine.com/active/goodsInfo/{}/{}".format(goods_id, activity_id)
        sec_header['Token'] = access_token
        sec_header['Origin'] = 'https://m.o2o.yesmywine.com'
        data = {"activity_id": activity_id, "addr_id": addr_id, "goods_id": goods_id}
        res = self.get_json(self.yemaijiu_activity_yuyue_url, headers=sec_header, json=data)
        self.logger.info(
            '函数名:{},功能:{},结果:{},参数:{},请求头:{}'.format(sys._getframe().f_code.co_name, '活动id下的商品预约', res, data,
                                                     sec_header))
        if res == -1:
            return 0, '网络错误'
        if res.get("code") == 0 and res.get("msg") == 'success':
            return 1, '成功'
        else:
            return 0, res['msg']

    def api_yuyue_create_order(self, access_token, activity_id, addr_id, goods_id):
        # 抢购
        sec_header = self._get_headers()
        sec_header['Host'] = "mk-ys.yesmywine.com"
        sec_header['Referer'] = "https://m.o2o.yesmywine.com/confirmOrder/{}/{}".format(goods_id, activity_id)
        sec_header['Token'] = access_token
        sec_header['Origin'] = 'https://m.o2o.yesmywine.com'
        data = {"accessToken": access_token, "activity_id": activity_id, "goods_id": goods_id, "shop_id": 1,
                "addr_id": addr_id, "quantity": 1, "dlyType": 4, "ziti_mobile": "",
                "payment_type": "online", "source_from": "wap", "mode": "rushbuy"}
        res = self.get_json(self.yemaijiu_order_create_url, headers=sec_header, json=data)
        self.logger.info(
            '函数名:{},功能:{},结果:{},参数:{},请求头:{}'.format(sys._getframe().f_code.co_name, '抢购下单', res, data, sec_header))
        if res == -1:
            return 0, '网络错误'
        if res.get("code") == 0 and res.get("msg") == 'success':
            return 1, '成功'
        else:
            return 0, res['msg']

    def api_yuyue_create_order_cart(self, access_token, addr_id):
        # 购物车下单
        sec_header = self._get_headers()
        sec_header['Host'] = "o2o.yesmywine.com"
        sec_header['Referer'] = "https://m.o2o.yesmywine.com/checkout/fastbuy/".format(addr_id)
        sec_header['Token'] = access_token
        sec_header['Origin'] = 'https://m.o2o.yesmywine.com'
        timestamp = str(int(time.time() * 1000))
        content = str(addr_id) + str(timestamp)
        m5 = md5()
        m5.update(content.encode("utf-8"))
        md5_cart_info = m5.hexdigest().lower()
        data = {"accessToken": access_token, "mode": "fastbuy", "md5_cart_info": md5_cart_info, "addr_id": addr_id,
                "payment_type": "online", "source_from": "wap", "shop_id": 1, "dlyType": "4", "appointmentTime": [],
                "shipping_type": "[{\"shop_id\":1,\"type\":\"express\",\"dlyType\":\"4\"}]", "invoice_type": "notuse",
                "use_points": 0,
                "invoice_content": "{\"title\":\"individual\",\"company_name\":\"\",\"company_address\":\"\",\"registration_number\":\"\",\"bankname\":\"\",\"bankaccount\":\"\",\"company_phone\":\"\"}",
                "can_use_deposit": "0.00", "mark": "", "ziti_mobile": "13530039446", "format": "json", "v": "v1",
                "method": "trade.create"}
        res = self.get_json(self.yemaijiu_url, headers=sec_header, json=data)
        self.logger.info(
            '函数名:{},功能:{},结果:{},参数:{},请求头:{}'.format(sys._getframe().f_code.co_name, '购物车下单', res, data, sec_header))
        if res == -1:
            return 0, '网络错误'
        if res.get("errorcode") == 0:
            return 1, '成功'
        else:
            return 0, res['msg']


kuai_api = KuaiAPI()
yemai_api = YeMaiAPI()
yuan_api = YuanAPI()
if __name__ == "__main__":
    a = YeMaiAPI()
    # print(yuan_api.get_hostname())
    # print(yuan_api.device_str())
    # yuan_api.exe_check()
    # yuan_api.install()
    yuan_api.add_dingshi('18542', '2022-02-02 02:02:02', 'token', '131')
    # yuan_api.qj_success('18323680105','asadadwzcwaczsazxaszxda')
    # yuan_api.exe_check()
    # yuan_api.exe_check()
    # yuan_api.exe_check()
    # ip = '106.117.130.60:21290'
    # r = requests.get('https://www.yesmywine.com/', proxies={'http': 'http://'+ ip, 'https':'http://'+ ip})
    # print(r.text)
    # a.api_sms('18707682907')
    # a.api_login('18707682907','873897')
    # token = 'b89cc601da16757aec401bfba39d671d94ada891ee20c4face19aa755bbf999f'
    # a.api_huiyuan_list(token)
    # {'errorcode': 0, 'msg': '', 'data': {'gradeInfo': {'grade_id': 1, 'experience': 0, 'grade_name': '普通会员', 'grade_logo': 'http://images.bbc.shopex123.com/images/4c/33/d1/edf40abb6a51123105830097c500f77469c35140.png'}, 'wait_pay_num': 0, 'wait_send_goods_num': 0, 'wait_confirm_goods_num': 0, 'canceled_num': 0, 'notrate_num': 0, 'coupon_num': 0, 'point': 0, 'cur_symbol': {'sign': '￥', 'decimals': 2}, 'deposit': 0, 'username': '18323680105', 'name': '18323680105', 'user_pic': '', 'commission_status': False, 'is_autonym': 0, 'hongbaoCount': 0, 'messageNumber': 0, 'plus': {'plus': 0, 'start_time': '', 'end_time': '', 'image': 'https://gedevip.oss-cn-beijing.aliyuncs.com/super-admin/2007220557110121.jpg', 'plus_type': 0}, 'consumer_mobile': '4008208060'}}
    # a.api_order_list(token,1,1)
    # a.api_order_list(token,2,1)
    # a.api_order_list(token,3,1)
    # a.api_order_detail(token,'3733409000095854')
    # a.api_address_list(token)
    # api_order_list {'errorcode': 0, 'msg': '', 'data': {'list': [{'addr_id': 403720, 'user_id': 333207, 'name': '龙肆', 'area': '广东省/深圳市/南山区', 'addr': '3111311', 'zip': None, 'tel': None, 'mobile': '18203048656', 'def_addr': 1, 'mapAddr': '广东省深圳市南山区新屋村东区青年宿舍113室,深圳市,辰宛亭便利店,22.568667,113.968485', 'addressValue': None, 'tag': 'no', 'subscribe_day': None, 'create_time': 1647572368, 'modified_time': 1647572368, 'region_id': '440000,440300,440305', 'addrdetail': '广东省深圳市南山区新屋村东区青年宿舍113室辰宛亭便利店3111311', 'lng': '113.968485', 'lat': '22.568667'}], 'count': {'nowcount': 1, 'maxcount': 20}}}

    # a.api_address_add(token,'广东省深圳市南山区','新屋村东区青年宿舍113室','18203048656','龙肆')
    # a.api_address_list(token)
    # api_order_list {'errorcode': 0, 'msg': '', 'data': {'status': 'success'}}
    # a.api_address_delete('9b02866ac973046e8775c7bea6c2fd2694ada891ee20c4face19aa755bbf999f','403721')
    # a.api_address_delete('9b02866ac973046e8775c7bea6c2fd2694ada891ee20c4face19aa755bbf999f','403720')
    # api_order_list {'errorcode': 0, 'msg': '', 'data': {'status': 'success'}}
    # a.api_point_detail(token)
    # a.api_point_checkinadd(token)
    # {"errorcode":0,"msg":"","data":{"checkinPointNum":"1"}}
    # {'errorcode': '10000', 'msg': '不可重复签到', 'data': {}}
    # a.api_coupon_list(token, 1, 1)
    # a.api_point_duihuan_list(token,1)
    # a.api_coupon_center(token,1,'all')
    # a.api_coupon_get(token,296,'platform')
    # a.api_real_auth(token,'','500236199303223232')
    # a.api_activity_goods(token, 145)
    # api_activity_goods {'code': 0, 'msg': 'success', 'data': {'id': 145, 'points_activity_id': None, 'type': 1, 'name': '新版预约购买', 'desc': '', 'poster_url': 'https://gedevip.oss-cn-beijing.aliyuncs.com/super-admin/2103010833603335.jpg', 'status': 1, 'end_time': 1672502399, 'goods': [{'activity_goods_id': 632, 'activity_id': 145, 'goods_id': 148054, 'goods_pic_url': 'https://o2o.yesmywine.com/images/62/d3/fe/b18c6e191bd814448076c84a522a34f5d575efc1.jpg', 'goods_name': '飞天53%vol500ml贵州茅台酒（带杯）', 'sub_integral': 2000, 'activity_price': 149900, 'goods_price': 149900, 'video_url': '', 'video_cover': '', 'year_max_num': 12}]}}
    # a.api_activity_good_detail(token,"145","148054","333207")
    # api_activity_good_detail {'code': 0, 'msg': 'success', 'data': {'goods_pic_url': [{'img': 'https://o2o.yesmywine.com/images/62/d3/fe/b18c6e191bd814448076c84a522a34f5d575efc1.jpg', 'format': 'image'}, {'img': 'https://o2o.yesmywine.com/images/cb/c7/e8/122caad56b4c030f472d11646bacfcfc0ee5bb72.jpg', 'format': 'image'}, {'img': 'https://o2o.yesmywine.com/images/04/68/c4/347583c0ea6328d3461bb6c17b828db601dcbec1.jpg', 'format': 'image'}, {'img': 'https://o2o.yesmywine.com/images/5c/05/bf/7a550b5389123a9b9fc88b8cd886fcb2a8cab511.jpg', 'format': 'image'}, {'img': 'https://o2o.yesmywine.com/images/27/52/d7/dab03efa86af34a5dad3c4a4b0edf95212c25628.jpg', 'format': 'image'}], 'image_default_id': 'https://o2o.yesmywine.com/images/62/d3/fe/b18c6e191bd814448076c84a522a34f5d575efc1.jpg', 'activity_id': 145, 'purchase_limit': 2, 'goods_id': 148054, 'goods_name': '飞天53%vol500ml贵州茅台酒（带杯）', 'goods_price': 149900, 'goods_sku': 'BJ22A0052', 'sub_integral': 2000, 'reserve_first_time': 1647745200, 'reserve_last_time': 1647781200, 'pay_first_time': 1647828000, 'pay_last_time': 1647831599, 'now_time': 1647778092, 'wap_desc': '<p>\n<img src="https://o2o.yesmywine.com/images/53/94/ce/6d20e829f86b539aca9eded6135d66732e00a1e6.jpg">\n<img src="https://o2o.yesmywine.com/images/a3/31/3c/a10a4cd288c98b0b4cc04deb880df9f8f1e9c644.jpg"></p>', 'activity_status': 0, 'status': 1, 'is_buy': 0, 'is_subscribe': 0, 'is_check': 0, 'point_count': '', 'type': 1, 'points_activity_id': 0}}
    # a.api_activity_good_yuyue(token,"145",'405243',"148054")
    # a.api_yuyue_create_order(token,145,405243,148054)
    # 我的账号 没到时间时间：2022-03-22 16:57:03,158，级别：INFO，输出：函数名:api_yuyue_create_order,功能:抢购下单,结果:{'code': 1006190, 'msg': '很遗憾，您没有抢到', 'data': '', 'trace': ''},参数:{'accessToken': 'b89cc601da16757aec401bfba39d671d94ada891ee20c4face19aa755bbf999f', 'activity_id': 145, 'goods_id': 148054, 'shop_id': 1, 'addr_id': 404839, 'quantity': 1, 'dlyType': 4, 'ziti_mobile': '', 'payment_type': 'online', 'source_from': 'wap', 'mode': 'rushbuy'},请求头:{'bbc-sec': '8e65db29d1dae707b1bffe83f0312641', 'bbc-timestamp': '1647939422883', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1', 'Host': 'mk-ys.yesmywine.com', 'Accept': '*/*', 'Content-Type': 'application/json', 'Accept-Encoding': 'gzip,deflate', 'Accept-Language': 'zh-CN,en-US;q=0.9', 'Origin': 'https://m.o2o.yesmywine.com', 'Referer': 'https://m.o2o.yesmywine.com/confirmOrder/148054/145', 'Token': 'b89cc601da16757aec401bfba39d671d94ada891ee20c4face19aa755bbf999f'}
    # 时间：2022-03-22 17:07:06,988，级别：INFO，输出：函数名:api_yuyue_create_order,功能:抢购下单,结果:{'code': 1006130, 'msg': '前方拥堵，请稍后再试.', 'data': '', 'trace': ''},参数:{'accessToken': 'b89cc601da16757aec401bfba39d671d94ada891ee20c4face19aa755bbf999f', 'activity_id': 145, 'goods_id': 148054, 'shop_id': 1, 'addr_id': 404839, 'quantity': 1, 'dlyType': 4, 'ziti_mobile': '', 'payment_type': 'online', 'source_from': 'wap', 'mode': 'rushbuy'},请求头:{'bbc-sec': '6abfc6cf6da11ef73148a72c7c01aa26', 'bbc-timestamp': '1647940026558', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1', 'Host': 'mk-ys.yesmywine.com', 'Accept': '*/*', 'Content-Type': 'application/json', 'Accept-Encoding': 'gzip,deflate', 'Accept-Language': 'zh-CN,en-US;q=0.9', 'Origin': 'https://m.o2o.yesmywine.com', 'Referer': 'https://m.o2o.yesmywine.com/confirmOrder/148054/145', 'Token': 'b89cc601da16757aec401bfba39d671d94ada891ee20c4face19aa755bbf999f'}
    # api_activity_good_yuyue {'code': 10014018, 'msg': '没有实名', 'data': '', 'trace': ''}

    b = KuaiAPI()
    # api_test = {
    #     '登录测试': a.api_login('laoban', 'laoban'),
    #
    # }
    # kuai_test = {
    #     '余额查询': b.get_balance('943080639206430', 'zqxqds1erup2fb4b5c1pkjn7jlt5vm9t'),
    #
    # }
    # b.get_balance('973080651860927','se6bebfsio8ox364fy9qzt6shp4ey9gm')
    # b.get_order_info('973080651860927','se6bebfsio8ox364fy9qzt6shp4ey9gm')
    # b.get_order_info('943080639206430', 'zqxqds1erup2fb4b5c1pkjn7jlt5vm9t')
    # b.get_order_info('923071870565399', 'ajd7nqxbi7gv8b81fu1iz3yxuvvxpxlj')
    # b.get_order_info('931836457332093', 'bkh1c809zxsf8h8xwia4wmk7y0kuee4o')
    # b.get_order_info('941827647993345', 'xthkyakayo1q79mt0j52bq50z1vwe6do')
    # b.get_order_info('901715501690712', '17y42w7qtfc44ypijvr3165qn12iljff')
    # b.get_order_info('921698305317046', '8sk7ydf8iewj98s4fzqnhq0xjx4yn5l6')
    # b.get_order_info('911638021538727', 'aepu2vixgyf81ackrtm8e0di7jdzqxkv')
    # b.get_dps_balance('973080651860927', 'se6bebfsio8ox364fy9qzt6shp4ey9gm')
    # b.get_dps('973080651860927', 'se6bebfsio8ox364fy9qzt6shp4ey9gm', 5)
    # b.get_kps('973080651860927', 'se6bebfsio8ox364fy9qzt6shp4ey9gm', 5)
